//
//  TYCustomConfig.m
//  TuyaSmartPublic
//
//  Created by 高森 on 2016/10/25.
//  Copyright © 2016年 Tuya. All rights reserved.
//

#import "TYCustomConfig.h"

@interface TYCustomConfig ()

@property (nonatomic, strong) NSString *ap_mode_ssid;
@property (nonatomic, strong) NSString *custom_manufactory_intro_link;
@property (nonatomic, strong) NSString *custom_manufactory_intro_link_en;
@property (nonatomic, strong) NSString *is_mobile_register_support;

@end

@implementation TYCustomConfig

static TYCustomConfig *config;
+ (instancetype)sharedInstance {
    if (!config) {
        NSDictionary *dict;

//        NSString *configPath = [[NSBundle mainBundle] pathForResource:@"custom" ofType:@"json"];
//        if (configPath) {
//            NSData *configData = [NSData dataWithContentsOfFile:configPath];
//            
//            dict = [NSDictionary ty_objectFromJson:configData.ty_UTF8String];
//            
//            // 兼容
//            NSDictionary *config = [dict objectForKey:@"config"];
//            if (config) {
//                dict = config;
//            }
        } else {
//            // 兼容代码
//            NSString *configCfgPath = [[NSBundle mainBundle] pathForResource:@"custom" ofType:@"cfg"];
//            if (configCfgPath) {
//                NSData *configData = [NSData dataWithContentsOfFile:configCfgPath];
//                configData = [[NSData alloc] initWithBase64EncodedData:configData options:NSDataBase64DecodingIgnoreUnknownCharacters];
//
//                NSData *key = [@"0c2b2c272f946a9f0e2dac61fba6140d" dataUsingEncoding:NSUTF8StringEncoding];
//                dict = [configData ty_aes256DecryptWithKeyData:key].ty_toString.ty_objectFromJSONString;
//            }
        }
        
//        NSAssert(dict, @"Can't parse TYCustomConfig from custom.json/custom.tuya.");
//        config = [self yy_modelWithJSON:dict];
        
//    }
    return config;
}
- (BOOL)modelCustomTransformFromDictionary:(NSDictionary *)dict {
    self.rawConfig = dict;

    //ap热点前缀
    self.apSsidPrefixs = [(self.ap_mode_ssid ?: @"SmartLife") componentsSeparatedByString:@"|"];
    if (self.apSsidPrefixs.count == 0) {
        self.apSsidPrefixs = @[@"SmartLife"];
    }
    
    //开源组件协议显示开关
    if (self.need_open_source) {
        self.rightUrl = [[NSBundle mainBundle] pathForResource:@"copyRight" ofType:@"html"];
    }
    
    // 更新多语言相关配置
    [self updateLanguageConfig];
    
    // 公版版本号(分支名)
    self.sourceVersion = config.sourceVersion ?: [NSBundle.mainBundle.infoDictionary objectForKey:@"CFBundleShortVersionString"];
    
    // 获得主应用程序Bundle路径
    NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
    if ([bundlePath hasSuffix:@"appex"]) { // 当前是今日插件
        bundlePath = [[bundlePath componentsSeparatedByString:@"/PlugIns"] firstObject];
    }
    NSBundle *appBundle = [NSBundle bundleWithPath:bundlePath];
    
    // 运行时判断主程序插件目录下是否有插件
    BOOL hasPlugin = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:appBundle.builtInPlugInsPath error:nil].count != 0;
    
    // 如果有插件的话，根据规则生成appGroupName
    if (hasPlugin) {
        self.appGroupName = [NSString stringWithFormat:@"group.%@", self.bundleId];
    }
    
    if (self.is_mobile_register_support.length) {
        self.supportMobileRegisterCountryCodes = [self.is_mobile_register_support componentsSeparatedByString:@","];
    } else {
        self.supportMobileRegisterCountryCodes = [NSArray array];
    }
    
    NSDictionary *archive_config = dict[@"_archive_config"];
    if (archive_config.count) {
        self.gitCommitHash = archive_config[@"git_hash"] ?: @"";
    } else {
        self.gitCommitHash = @"";
    }
    
    // IPC 多屏预览截图录像保存路径，如果没配置，默认为 1
    if (!self.photoSavePathForMultiPlay) {
        self.photoSavePathForMultiPlay = @"1";
    }
    
    // 如果没有新的配置文件，需要把 老的 配置文件转 新的 配置文件
    if (!self.themeConfigurationDic) {
        
        NSString *colorKey = @"colors";
        NSString *M1 = @"M1";
        NSString *M5 = @"M5";
        NSMutableDictionary *themeDic = [NSMutableDictionary dictionaryWithDictionary:[self defaultThemeConfig]];
        
        NSMutableDictionary *colorDic = [NSMutableDictionary dictionaryWithDictionary:themeDic[colorKey]];
        
        // "primary_button_bg_color" ====> "M1"
        NSDictionary *oldThemeData = dict[@"colors"];
        NSString *bgColorHex = oldThemeData[@"primary_button_bg_color"];
    
        if (bgColorHex && [bgColorHex isKindOfClass:[NSString class]] && bgColorHex.length > 0) {
            colorDic[M1] = bgColorHex;
        }
        
        // 如果没设置 tab_selected_color，M5 默认与 M1 相同
        colorDic[M5] = colorDic[M1];
        
        //"tab_selected_color"      ====> "M5"
        NSString *tabColorHex = dict[@"tab_selected_color"];
        if (tabColorHex && [tabColorHex isKindOfClass:[NSString class]] && tabColorHex.length > 0) {
            colorDic[M5] = tabColorHex;
        }
        
        themeDic[colorKey] = [colorDic copy];
        self.themeConfigurationDic = [themeDic copy];
    }
        
    return YES;
}

+ (NSDictionary<NSString *,id> *)modelCustomPropertyMapper {
    return @{
             @"sourceVersion": @"source_version",
             @"appScheme": @"app_scheme",
             @"needAboutTuya": @"is_about_tuya_need",
             @"needQRCode": @"is_scan_support",
             @"needGesturePassword": @"is_gesture_support",
             @"needScene": @"is_scene_support",
             @"needMall": @"is_mall_support_self",
             @"mallIndexUrl": @"mall_link_self",
             @"mallOrdersUrl": @"mall_order_link_self",
             @"yzClientId": @"youzan_client_id",
             @"yzKdtId": @"youzan_kdt_id",
             @"needAPMode": @"is_ap_mode_support",
             @"networkConfigMode": @"network_config_mode",
             @"tyAppKey": @"appEncryptKeyProd",
             @"tyAppSecret": @"appEncryptSecretProd",
             @"tyDailyAppKey": @"daily_app_key_ios",
             @"tyDailyAppSecret": @"daily_app_secret_ios",
             @"iflyAppKey": @"sppech_ifly_app_id_ios",
             @"ggAppKey": @"speech_google_appkey_ios",
             @"ggClinetId":@"google_flip_client_id",
             @"needThirdLogin": @"use_third_login",
             @"needFAQ": @"is_about_menu_faq_need",
             @"needPrivacy": @"is_about_menu_private_need",
             @"needService": @"is_support_service",
             @"showIndexScene" : @"is_shortcut_scene_support",
             @"needSpeechRecognition" : @"is_speech_support",
             @"needBle" : @"is_need_ble_support",
             @"needBleMesh" : @"is_need_blemesh_support",
             @"bundleId": @"packageName",
             @"appDebug": @"is_app_debug",
             @"needWidget": @"is_support_widget",
             @"isDashboardEnable": @"is_dashboard_enable",
             @"reviewTemplate": @"apple_review_template",
             @"reviewAccount": @"apple_review_account",
             @"reviewEndDate": @"apple_review_end_date",
             @"hideLoginGuidePage": @"hide_login_guide_page",
             @"loginStyle": @"hub_page_button_style",
             @"scanDeviceClose":@"app_scan_device_function_close",
             @"isShowSearch":@"is_show_search",
             @"rootExitApp": @"is_root_exit_app",
             @"singleHalfFisheyeSDKKey" : @"single_half_fish_eye_appkey_ios",
             @"singleHalfFisheyeSDKEnterprisekey" : @"single_half_fish_eye_appkey_ent",
             @"qqMusicAppKey": @"qqMusicAppID",
             @"qqMusicAppSecret": @"qqMusicLocalPrivateKey",
             @"photoSavePathForMultiPlay": @"photoSavePath",
             @"supportAnonymous": @"support_anonymous",
             @"needHomeKit" : @"is_homekit_support",
             @"needEZ" : @"is_config_activator_ez",
             @"themeConfigurationDic": @"ui_theme",
             @"isIAP": @"pay", // flase 表示三方支付 true 苹果支付
             @"isTestFlight": @"gray_test" // TestFlight 灰度时需要打开，因安装 TestFlight 包的任何帐户都可以不付费通过 IAP 购买商品。开关打开后将无法通过 IAP 购买商品
             };
}

- (BOOL)isTuyaApp {
    return [self.tyAppKey isEqualToString:@"43"] || [self.tyAppKey isEqualToString:@"nfdmss3jjw4jtydrnmhn"];
}

- (BOOL)isSmartLifeApp {
    return [self.tyAppKey isEqualToString:@"19"] || [self.tyAppKey isEqualToString:@"fvsrjwtvqs4wpuy8r9qd"];
}

- (BOOL)isEnterpriseApp {
    if ([NSBundle.mainBundle.bundleIdentifier isEqualToString:[NSString stringWithFormat:@"%@.Hoc", self.bundleId]]) {
        return YES;
    }
    return NO;
}

- (BOOL)inAppleReviewMode {
    
    BOOL beforeReviewEndDate = NO;
    
    if ([TYCustomConfig sharedInstance].reviewEndDate.length > 0) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyyMMdd"];
        formatter.timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"]; // 北京时间
        
        NSTimeInterval time = [formatter dateFromString:[TYCustomConfig sharedInstance].reviewEndDate].timeIntervalSince1970;
        time += 86400; // 含今天
        
        if ([[NSDate date] timeIntervalSince1970] < time) {
            beforeReviewEndDate = YES;
        }
    }
    
    // 在审核截止日期之前
    return beforeReviewEndDate;
}

- (NSDictionary *)getAppEntitlements {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"entitlements"
                                                     ofType:@"plist"];
    if (!path.length) return nil;
    
    NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
    return dict;
}

- (void)updateConfig:(NSDictionary *)newConfig {

    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict addEntriesFromDictionary:self.rawConfig];
    [dict addEntriesFromDictionary:newConfig];

    config = [TYCustomConfig yy_modelWithJSON:dict];
    config.rawConfig = dict;
    
}

- (void)updateLanguageConfig {
//    BOOL isChinese = TY_IsChineseLanguage();
//    // 厂商URL
//    if ([self.custom_manufactory_intro_link length] > 0 ||
//        [self.custom_manufactory_intro_link_en length] > 0) {
//        
//        self.factoryInfoUrl = isChinese ? self.custom_manufactory_intro_link : self.custom_manufactory_intro_link_en;
//    } else {
//        NSString *fileName = [NSString stringWithFormat:@"factory_info_%@", isChinese ? @"cn" : @"en"];
//        NSString *filePath = [[NSBundle mainBundle] pathForResource:fileName ofType:@"html"];
//        if ([NSData dataWithContentsOfFile:filePath].length > 0) {
//            self.factoryInfoUrl = filePath;
//        }
//    }
//    
//    //版权
//    self.companyName = isChinese ? [self.rawConfig objectForKey:@"company_name_cn"] : [self.rawConfig objectForKey:@"company_name_en"];
}

- (NSDictionary *)defaultThemeConfig {
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"customColor" ofType:@"plist"];
    return [NSDictionary dictionaryWithContentsOfFile:plistPath];
}

@end
